"""
Phase 5: KAOPEN & Income Interactions
======================================
Z x KAOPEN on capital_intensity, labor_productivity;
OECD vs non-OECD for automation measures;
Income tercile heterogeneity (gdp_pc_ppp terciles).
"""

import pandas as pd
import numpy as np
from pathlib import Path
import sys
import warnings
warnings.filterwarnings('ignore')

PROJECT_DIR = Path(__file__).resolve().parent.parent
ROOT_DIR = PROJECT_DIR.parent
sys.path.insert(0, str(ROOT_DIR / "multilateral" / "src"))
from model import PanelGLS

DATA = PROJECT_DIR / "data" / "processed"
OUT_TABLES = PROJECT_DIR / "output" / "tables"
OUT_TABLES.mkdir(parents=True, exist_ok=True)

OECD = {
    'AUS', 'AUT', 'BEL', 'CAN', 'CHL', 'COL', 'CRI', 'CZE', 'DNK', 'EST',
    'FIN', 'FRA', 'DEU', 'GRC', 'HUN', 'ISL', 'IRL', 'ISR', 'ITA', 'JPN',
    'KOR', 'LVA', 'LTU', 'LUX', 'MEX', 'NLD', 'NZL', 'NOR', 'POL', 'PRT',
    'SVK', 'SVN', 'ESP', 'SWE', 'CHE', 'TUR', 'GBR', 'USA',
}


def stars(p):
    if p < 0.01: return '***'
    if p < 0.05: return '**'
    if p < 0.1: return '*'
    return ''


def fmt(val, se, p):
    s = stars(p)
    return f"{val:.4f}{s}", f"({se:.4f})"


def run_panel_gls(df, y_var, x_vars, label):
    """Run PanelGLS and return results dict."""
    cols = [y_var] + x_vars + ['iso3', 'year']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  {label}: insufficient obs ({len(sub)}), skipping")
        return None

    gls = PanelGLS()
    y = sub[y_var].values
    X = sub[x_vars].values
    try:
        gls.fit(y, X, sub['iso3'].values, sub['year'].values)
    except Exception as e:
        print(f"  {label}: GLS failed ({e}), skipping")
        return None

    result = {
        'model': label,
        'n_obs': gls.n_obs,
        'n_countries': gls.n_countries,
        'r_squared': gls.r_squared,
        'rho': gls.rho,
    }
    print(f"\n  {label} (N={gls.n_obs}, R²={gls.r_squared:.4f})")
    for i, name in enumerate(x_vars):
        sig = stars(gls.pvalues[i])
        print(f"    {name:30s} {gls.beta[i]:8.4f} ({gls.se[i]:.4f}) {sig}")
        result[f'{name}_coef'] = gls.beta[i]
        result[f'{name}_se'] = gls.se[i]
        result[f'{name}_p'] = gls.pvalues[i]

    return result


def write_table(results, filename, title):
    """Write regression results as markdown table."""
    if not results:
        return

    lines = [f"# {title}\n"]

    all_vars = []
    for r in results:
        for k in r:
            if k.endswith('_coef'):
                vname = k.replace('_coef', '')
                if vname not in all_vars:
                    all_vars.append(vname)

    model_labels = [r['model'] for r in results]
    header = "| Variable | " + " | ".join(model_labels) + " |"
    sep = "|:---|" + "|".join(["---:" for _ in results]) + "|"
    lines.append(header)
    lines.append(sep)

    for var in all_vars:
        coef_row = f"| {var} |"
        se_row = "| |"
        for r in results:
            if f'{var}_coef' in r:
                c, s = fmt(r[f'{var}_coef'], r[f'{var}_se'], r[f'{var}_p'])
                coef_row += f" {c} |"
                se_row += f" {s} |"
            else:
                coef_row += " |"
                se_row += " |"
        lines.append(coef_row)
        lines.append(se_row)

    lines.append("|:---|" + "|".join(["---:" for _ in results]) + "|")
    n_row = "| N |"
    r2_row = "| R² |"
    nc_row = "| Countries |"
    for r in results:
        n_row += f" {r['n_obs']} |"
        r2_row += f" {r['r_squared']:.4f} |"
        nc_row += f" {r['n_countries']} |"
    lines.append(n_row)
    lines.append(r2_row)
    lines.append(nc_row)

    lines.append("\n*Panel GLS with country and year fixed effects. "
                 "Standard errors in parentheses.*")
    lines.append("*\\*p<0.1, \\*\\*p<0.05, \\*\\*\\*p<0.01*")

    path = OUT_TABLES / filename
    path.write_text('\n'.join(lines))
    print(f"\n  Saved: {path}")


# ── 1. KAOPEN × Demographics on Automation Measures ────────────────

def kaopen_automation(df):
    """Z x KAOPEN interactions on capital_intensity and labor_productivity."""
    print("\n" + "=" * 60)
    print("1. KAOPEN x DEMOGRAPHICS ON AUTOMATION MEASURES")
    print("=" * 60)

    df = df.copy()
    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth']

    # Ensure interaction terms exist
    for z in ['Z_1', 'Z_2', 'Z_3']:
        col = f'{z}_x_kaopen'
        if col not in df.columns:
            df[col] = df[z] * df['kaopen']

    results_all = []

    # Determine available automation dependent variables
    auto_dvs = []
    for var in ['capital_intensity', 'labor_productivity', 'capital_per_worker']:
        if var in df.columns and df[var].notna().sum() > 100:
            auto_dvs.append(var)

    # If no automation-specific vars, use gross_investment_gdp as proxy
    if not auto_dvs:
        print("  No automation-specific DVs found; using gross_investment_gdp")
        auto_dvs = ['gross_investment_gdp']

    for dv in auto_dvs:
        print(f"\n--- Dependent variable: {dv} ---")

        # M1: Z only
        r = run_panel_gls(df, dv,
                          ['Z_1', 'Z_2', 'Z_3'] + controls,
                          f'{dv}: Z')
        if r: results_all.append(r)

        # M2: Z + KAOPEN
        r = run_panel_gls(df, dv,
                          ['Z_1', 'Z_2', 'Z_3', 'kaopen'] + controls,
                          f'{dv}: Z+KA')
        if r: results_all.append(r)

        # M3: Z + Z x KAOPEN
        r = run_panel_gls(df, dv,
                          ['Z_1', 'Z_2', 'Z_3', 'kaopen',
                           'Z_1_x_kaopen', 'Z_2_x_kaopen', 'Z_3_x_kaopen'] + controls,
                          f'{dv}: Z*KA')
        if r: results_all.append(r)

    write_table(results_all, "kaopen_automation.md",
                "KAOPEN Interactions: Demographics and Automation")

    # OECD vs Non-OECD split
    print("\n--- OECD vs Non-OECD ---")
    df['is_oecd'] = df['iso3'].isin(OECD).astype(int)
    oecd_df = df[df['is_oecd'] == 1].copy()
    non_oecd_df = df[df['is_oecd'] == 0].copy()

    results_oecd = []
    x_vars = ['Z_1', 'Z_2', 'Z_3', 'kaopen',
              'Z_1_x_kaopen', 'Z_2_x_kaopen', 'Z_3_x_kaopen'] + controls

    for dv in auto_dvs:
        for sub_df, label in [(oecd_df, 'OECD'), (non_oecd_df, 'Non-OECD')]:
            r = run_panel_gls(sub_df, dv, x_vars, f'{dv}: {label}')
            if r: results_oecd.append(r)

    if results_oecd:
        write_table(results_oecd, "kaopen_automation_oecd.md",
                    "KAOPEN x Demographics: OECD vs. Non-OECD")

    return df


# ── 2. Income Tercile Heterogeneity ────────────────────────────────

def income_tercile_automation(df):
    """Run main automation regressions split by GDP per capita terciles."""
    print("\n" + "=" * 60)
    print("2. INCOME TERCILE HETEROGENEITY")
    print("=" * 60)

    df = df.copy()
    controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'kaopen']

    # Compute income terciles
    if 'gdp_pc_ppp' not in df.columns:
        print("  gdp_pc_ppp not available, skipping income terciles")
        return

    valid = df['gdp_pc_ppp'].notna()
    df.loc[valid, 'income_tercile'] = pd.qcut(
        df.loc[valid, 'gdp_pc_ppp'], 3,
        labels=['Low', 'Mid', 'High']
    )

    for tercile in ['Low', 'Mid', 'High']:
        n = (df['income_tercile'] == tercile).sum()
        n_c = df[df['income_tercile'] == tercile]['iso3'].nunique()
        print(f"  {tercile}: {n} obs, {n_c} countries")

    # Determine automation DVs
    auto_dvs = []
    for var in ['capital_intensity', 'labor_productivity', 'capital_per_worker']:
        if var in df.columns and df[var].notna().sum() > 100:
            auto_dvs.append(var)
    if not auto_dvs:
        auto_dvs = ['gross_investment_gdp']

    results = []

    for dv in auto_dvs:
        print(f"\n--- Dependent variable: {dv} ---")

        # Full sample baseline
        r = run_panel_gls(df, dv,
                          ['Z_1', 'Z_2', 'Z_3'] + controls,
                          f'{dv}: Full')
        if r: results.append(r)

        # By income tercile
        for tercile in ['Low', 'Mid', 'High']:
            sub = df[df['income_tercile'] == tercile].copy()
            r = run_panel_gls(sub, dv,
                              ['Z_1', 'Z_2', 'Z_3'] + controls,
                              f'{dv}: {tercile}')
            if r: results.append(r)

    write_table(results, "income_tercile_automation.md",
                "Income Tercile Heterogeneity: Demographics and Automation")


# ── Main ────────────────────────────────────────────────────────────

def main():
    print("=" * 70)
    print("PHASE 5: KAOPEN & INCOME INTERACTIONS")
    print("=" * 70)

    df = pd.read_csv(DATA / "automation_panel.csv")
    print(f"Panel: {len(df)} obs, {df['iso3'].nunique()} countries")
    print(f"Columns: {list(df.columns)}")

    # 1. KAOPEN x demographics on automation measures
    df = kaopen_automation(df)

    # 2. Income tercile heterogeneity
    income_tercile_automation(df)

    print("\n" + "=" * 70)
    print("PHASE 5 COMPLETE")
    print("=" * 70)


if __name__ == '__main__':
    main()
